package com.typing.battle.activity;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.typing.battle.R;
import com.typing.battle.listener.OnDataSyncCompleteListener;
import com.typing.battle.receiver.C2dmBroadcastReceiver;
import com.typing.battle.util.PreferenceMgr;
import com.typing.battle.util.ServerComunicationUtil;
import com.typing.battle.util.TypingSpeedCalculator;
import com.typing.battle.value.MessageDTO;
import com.typing.battle.value.ServerComunicationDTO;
import com.typing.battle.view.TimeAttackListView;

public class TypingBattleTimeAttackActivity extends TypingBattleRootActivity{
	private TextView sentence,ranking;
	private EditText input;
	private Button send;
	private LinearLayout layout;
	private Context mContext;
	private PreferenceMgr mgr;
	private TypingSpeedCalculator calculator;
	
	private boolean isFirstKey = false;
	
	private String _ID;
	private String orgStr;
	@Override
    protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.battle_time_attack);
        mgr = PreferenceMgr.getInstance(this);
        sentence = (TextView)findViewById(R.id.label_sentence);
        ranking = (TextView)findViewById(R.id.label_ranking);
        _ID = getIntent().getStringExtra("SENTENCE_ID");
        orgStr = getIntent().getStringExtra("SENTENCE");
        sentence.setText(orgStr);
        
        //ranking.setText(intent.getStringExtra("SENTENCE"));
        sentence.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					hideSoftKeyboard(v);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
        ranking.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					hideSoftKeyboard(v);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
        
        input = (EditText)findViewById(R.id.input_time_attack);
        input.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				// TODO Auto-generated method stub
				return true;
			}
		});
        input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				if (!isFirstKey) {
					isFirstKey = true;
					calculator = new TypingSpeedCalculator(orgStr);
				}
				Log.d("beforeTextChanged",""+s);
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				// Log.d("afterTextChanged",""+s);
			}
		});
        send = (Button)findViewById(R.id.btn_send_time_attack);
        send.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				timeAttackSend();
			}
		});
        setRanking();
	}
	private void setRanking(){
		ranking = (TextView)findViewById(R.id.label_ranking);
		ServerComunicationDTO dto = new ServerComunicationDTO();
		dto.setActionType(ServerComunicationUtil.TYPE_TIME_ATTACK_RANKING);
		dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_JSON);
		dto.setSentenceId(_ID);
		//dto.setSendType(C2dmBroadcastReceiver.TYPE_TYPING_RESULT);
		try {
			ServerComunicationUtil.serverAction(dto,mContext,this);
		} catch (Exception e) {
			Log.e("", "TYPE_CHAT_ROOM_DETAIL ERROR ::: "+e.getMessage());
			e.printStackTrace();
		}
	}
	public void timeAttackSend() {
		input = (EditText) findViewById(R.id.input_time_attack);
	
		try {
			// 메시지를 보낼때 sender(발급받은 ID, 토큰인증값, 메시지)
			calculator.endTyping(input.getText().toString());
			int[] result = calculator.calculate();
			Log.d("걸린시간", result[0] + "밀리세컨드");
			Log.d("타수", "" + result[1] + " 타  / 분");
			Log.d("정확도", "" + result[2] + "%");
			showNotify(result);
			calculator.reset();
			
			ServerComunicationDTO dto = new ServerComunicationDTO();
			dto.setActionType(ServerComunicationUtil.TYPE_TIME_ATTACK_INSERT);
			dto.setResponseType(ServerComunicationUtil.RETURN_TYPE_STRING);
			dto.setUserEmail(mgr.getData(PreferenceMgr.USER_EMAIL_KEY, ""));
			dto.setSentenceId(_ID);
			dto.setTypingTime("" + result[0]);
			dto.setTypingSpeed("" + result[1]);
			dto.setTypingAccuracy("" + result[2]);			
			dto.setSendType(C2dmBroadcastReceiver.TYPE_TYPING_RESULT);
			try {
				ServerComunicationUtil.serverAction(dto, mContext);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			input.setText("");
			isFirstKey = false;		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}			
		setRanking();
	}
	
	public void showNotify(int[] speed) {
		Toast toast = Toast.makeText(this, "타수 :" + speed[1] + "\n" + "정확도 :"
				+ speed[2], Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 150);
		toast.show();
	}
	
	public void hideSoftKeyboard(View input) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
	}
	
	@Override
	public void onSyncComplete(int resultCode, ServerComunicationDTO dto, Object resultObj) {
		if(resultCode == OnDataSyncCompleteListener.RESULT_SYNC_FAIL){
			if(resultObj!=null)
				ServerComunicationUtil.showNotify((String)resultObj, this);
		}else{
			if(dto.getActionType() == ServerComunicationUtil.TYPE_TIME_ATTACK_RANKING){
				JSONArray list = null;
				StringBuffer sb = new StringBuffer();
				try {
					list = (JSONArray)resultObj;
					if(list != null){
						for(int i=0;i<list.length();i++){
							JSONObject data = new JSONObject(list.get(i).toString());
							if(i != 0){
								sb.append("\n");
							}
							sb.append((i+1) + "위 : ");
							sb.append(data.get("email").toString() + " 님 ");
							sb.append("(");
							sb.append(data.get("speed").toString()+"타");
							sb.append("/");
							sb.append(data.get("accuracy").toString()+"%");
							sb.append(")");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				ranking.setText(sb.toString());
			}		
		}
		super.onSyncComplete(resultCode, dto, resultObj);
	}
}

